<script setup lang="ts">
import {
  ResourceGroupApi,
  ResourceGroupTreeVO
} from "@/api/resource/group";

const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'groupChild',
  checkStrictly: true,
  emitPath: false,
}

const emit = defineEmits(['change'])
const model = defineModel<number[] | number>({
  required: true
})
const list = ref<ResourceGroupTreeVO[]>([])
const treeList = ref<ResourceGroupTreeVO[]>([])

/** 填充父节点 */
const fullParentNode = (id: number | undefined) => {
  if (!id) return []

  const arr: number[] = []
  let currentNode = list.value.find((node) => node.id === id)
  while (currentNode) {
    arr.unshift(currentNode.id)
    currentNode = list.value.find((node) => node.id === currentNode?.parent)
  }

  return arr
}

onBeforeMount(async () => {
  const data = await ResourceGroupApi.getResourceGroupTreeList()
  treeList.value = data

  const convertList = (group: ResourceGroupTreeVO) => {
    group.groupChild.forEach((group) => convertList(group))

    // 清空子分组，只保留基本信息和资源内容
    const newGroup: ResourceGroupTreeVO = {
      ...group,
      groupChild: [],
    }
    list.value.push(newGroup)
  }
  data.forEach((group) => convertList(group))

  if (!Array.isArray(model.value)) {
    model.value = [model.value]
  }
  model.value = fullParentNode(model.value[0])
})

const handleChange = (id: number) => {
  emit('change', list.value.find((item) => item.id === id))
}

</script>

<template>
  <el-cascader
    class="w-full"
    v-model="model"
    :options="treeList"
    :props="cascaderProps"
    clearable
    @change="handleChange"
  />
</template>

<style scoped lang="scss">

</style>
